import Vue from 'vue';
import ElementUI from 'element-ui';
import ToolAddDialogComponent from './tool-add.dialog.component.vue';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

export class ToolAddDialogService {
  #fetcher = () => { };

  #createElement = () => {
    const element = document.createElement('div');
    document.body.appendChild(element);
    return element;
  };

  constructor(fetcher) {
    this.#fetcher = fetcher;
  }

  create({ title, query, confirmButtonClickHandler } = {}) {
    title || (title = '添加工具');
    query || (query = {});
    confirmButtonClickHandler || (confirmButtonClickHandler = (data = {}) => { });
    const App = Vue.extend(ToolAddDialogComponent);
    return (() => {
      const _this = this;
      return {
        mount: function () {
          const vm = new App({
            propsData: {
              title: title,
              query: query,
              visible: true,
              fetcher: _this.#fetcher
            }
          });
          const element = _this.#createElement();
          const destroy = () => {
            const element = vm.$el;
            if (element.parentNode) {
              element.parentNode.removeChild(element);
            }
          };
          vm.$on('destroy', destroy);
          vm.$on('confirm', confirmButtonClickHandler);
          vm.$mount(element);
          return {
            unmount: () => {
              destroy();
              return this;
            }
          };
        }
      };
    })();
  }
}
